﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using Core.Messages;
using Library.Logging;
using PostSharp.Aspects;
using Share.Enterprise.DI;

namespace Core.Aspects
{
    [Serializable]
    public class HandleServiceErrorAttribute : OnExceptionAspect
    {
        [NonSerialized]
        private ILogger logger;

        public override void RuntimeInitialize(MethodBase method)
        {
            logger = DIContext.CurrentContainer.GetInstance<ILogger>();
        }

        public override void OnException(MethodExecutionArgs args)
        {
            Type returnType = ((MethodInfo)args.Method).ReturnType;
            if(returnType == typeof(Response) || returnType.IsSubclassOf(typeof(Response)))
            {
                Response response = args.ReturnValue as Response;
                if (response == null)                
                    response = (Response)Activator.CreateInstance(returnType);                

                SetErrorResponse(response, args.Exception);
                args.ReturnValue = response;
                args.FlowBehavior = FlowBehavior.Return;
            }            
        } 

        protected void SetErrorResponse(Response response, Exception ex)
        {
            Guid ticket;
            logger.Log(ex, out ticket);
            response.Success = false;
            response.ShowNotification = true;

            #if DEBUG
                        response.ErrorMessage = ex.ToString();
            #else
                        response.ErrorMessage = string.Format("An error has occurred. Ticket : {0}", ticket);
            #endif
        }
    }
}
